<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>聊天窗口</title>
    <link rel="stylesheet" href="/css/style.css">
</head>
<body>

<div class="box">
    <div class="title">
        <h1>聊天窗口</h1>
    </div>
    <div class="message-list"></div>
    <div class="message">
        <textarea id="msg" autofocus></textarea>
        <button id="send">发送</button>
    </div>
</div>
<script>
    let btn = document.getElementById("send");
    let msg = document.getElementById("msg");
    let content = document.querySelector(".message-list");

    let user = '/images/user.jpg';
    let bot = '/images/bot.jpg';
    btn.onclick = function(){
        let value = msg.value.trimStart();
        // 字符串 是 空串的话 表示为 false
        if (value){
            msg.value = "";
            let q = value;

            // 内容格式化
            let result = formatHTML(value);


            // a = a + b -> a += b;
            content.innerHTML += "<div class='question'><span class='text'>" + result + "</span><img src='" + user + "'/></div>";
            // 回复
            fetch("/send", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json"
                },
                body: q
            }).then(function(response){
                return response.json();
            }).then(function(data){
                // console.log(data.choices[0].message.content);
                let result1 = data.choices[0].message.content;
                let resp = formatHTML(result1, 20);
                content.innerHTML += "<div class='answer'><img src='" + bot + "'/><span class='text'>" + resp + "</span></div>";
                // 滚动条
                content.scrollTop = content.scrollHeight;
            });

        }
        msg.focus(); // 聚焦到输入框
    }


    // 1. 通过键盘事件监听键盘的按下
    msg.onkeydown = function(event){
        // event 事件对象
        // 2. 判断是否按下了回车键 + alt
        if (event.key === "Enter" && event.altKey){
            // 3. 如果按下了回车键，就模拟点击发送按钮
            btn.click();
        }
    }

    function formatHTML(content, length = 20){
        let result = "";
        // 内容过长换行
        do{
            result += content.substring(0, length) + "<br/>";
            content = content.substring(length);
        }while(content.length > length);

        result += content;
        result = result.replaceAll(" ", "&nbsp;");
        // 换行符替换
        result = result.replaceAll("\n", "<br/>");
        return result;
    }

</script>
</body>
</html>